#include "../include/taskQueue.h"
#include "../include/threadPool.h"
#include "../include/task.h"

#include<iostream>

using std::cout;
using std::endl;

ThreadPool::ThreadPool(size_t threadNum,size_t capacity)
:_threadNum(threadNum)
,_threads()
,_capacity(capacity)
,_taskQueue(capacity)
,_isExit(false)
{


}

ThreadPool::~ThreadPool()
{

}

void ThreadPool::start()
{
	for(size_t i = 0;i < _threadNum;i++)
		_threads.push_back(thread(&ThreadPool::doTask,this));
}

void ThreadPool::stop()
{
	cout << "线程池正在准备退出\n";
	// 等待所有子线程执行完毕
	while(!_taskQueue.empty())
		std::this_thread::sleep_for(std::chrono::seconds(1));
	// 通知子线程，主线程即将退出
	_isExit = true;
	// 唤醒在等待任务的子线程，准备退出
	_taskQueue.wakeUp();
	// 等待所有子线程退出
	for(auto & x : _threads)
	{
		cout << x.get_id() << "---->线程正在退出\n";
		x.join();
	}
}

void ThreadPool::addTask(function<void()> && pTask)
{
	if(pTask)
		_taskQueue.push(std::move(pTask));
}

function<void()> ThreadPool::getTask()
{
	return _taskQueue.pop();
}

void ThreadPool::doTask()
{
	while(!_isExit)
	{
		auto pTask = getTask();
		if(pTask)
			pTask();
	}
}

